/*
   gulp 开发运行
   gulp creat:min:dist   压缩文件到 dist.min
   gulp creat:dist       拷贝文件到 dist
   gulp zip:dist.min     将dist.min 压缩zip
   gulp zip:dist         将dist 压缩zip

   gulp clean:dist       清除dist
   gulp clean:dist.min   清除dist.min
*/

var gulp = require('gulp')
var sass = require('gulp-sass')
var plumber = require('gulp-plumber')
// var csscomb = require('gulp-csscomb')
var zip = require('gulp-zip')
var htmlmin = require('gulp-htmlmin')
var csso = require('gulp-csso')
var imagemin = require('gulp-imagemin')
var notify = require('gulp-notify') //系统通知
var uglify = require('gulp-uglify')
var clean = require('gulp-clean')
var pump = require('pump');
var autoprefixer = require('gulp-autoprefixer')
var preprocess = require('gulp-preprocess')
var extender = require('gulp-html-extend')
var browserSync = require('browser-sync').create()
var reload = browserSync.reload;

var babel = require('gulp-babel');

// const imagemin = require('');

// gulp.task('default', () =>
//     gulp.src('src/images/*')
//         .pipe(imagemin())
//         .pipe(gulp.dest('dist/images'))
// );
// ===================开发阶段任务

// console.log(precess.argv)

//命令行输入 gulp 或 gulp任务名 + --参数名
//gulp --argu
console.log(process.argv) 

gulp.task('browserSyncServer',function(){
	var url = "index.html"

	try{
		if(/\.html$/.test(process.argv[2].slice(2))){
			url = process.argv[2].slice(2);
			console.log("成功访问" + url)
		}
	}catch(e){
        console.log("默认访问" + url);
	}
	
    browserSync.init({
        server: {
            baseDir: "./src/",
            index:url
        }
    });
})

gulp.task('extend', function (done) {
    gulp.src('./src/pages/template/standShopPages/*.html')
        .pipe(extender({annotations:true,verbose:false})) // default options 
        .pipe(gulp.dest('./src/pages')).on('end', function() {
         done && done()
    })
 
})

gulp.task('clean:dist',function(){
    return gulp.src('dist')
        .pipe(clean());
})
gulp.task('clean:dist.min',function(){
    return gulp.src('dist.min')
        .pipe(clean());
})

gulp.task('sass', function(done) {
    return gulp.src('src/sass/*.scss').pipe(plumber()).pipe(sass.sync().on('error', sass.logError)).pipe(autoprefixer({
        browsers: [
            '>1%',
            'last 4 versions',
            'Firefox ESR',
            'not ie < 9', // React doesn't support IE8 anyway
            'Android 2.3',
            'Android >= 4',
            'Chrome >= 20',
            'Firefox >= 24', // Firefox 24 is the latest ESR
            'Explorer >= 8',
            'iOS >= 6',
            'Opera >= 12',
            'Safari >= 6'
        ],
        cascade: false
    }))
    .pipe(sass({outputStyle: 'expanded'}).on('error', sass.logError))
    .pipe(gulp.dest('src/css')).on('end', function() {
        reload()
        done && done()
    })
})


gulp.task('watch', function(done) {
    return gulp.watch(['src/sass/**/*.scss','src/pages/template/**/*.html'], gulp.series('sass','extend')).on('end', function() {
        done && done() 
    })
})

gulp.task('es6', () => {
    return gulp.src('src/es6/**/*.js')
        .pipe(plumber({}, true, function(err){
            console.log('ERROR!!!!');
            console.log(err);
        }))
        .pipe(babel({
            presets: ['es2015']
        }))
        .pipe(gulp.dest('src/js/'));
});
// ===================压缩类任务

gulp.task('htmlmin', function() {
  return gulp.src(['src/*.html'])
    .pipe(htmlmin({collapseWhitespace: true}))
    .pipe(gulp.dest('dist.min'))
    .on('end', function(done) {
        done && done() 
    })
});

gulp.task('cssmin', function () {
    return gulp.src('src/css/*.css')
    .pipe(csso({
        restructure: false,
        sourceMap: true,
        debug: true
    }))
    .pipe(gulp.dest('dist.min/css'))
    .on('end', function(done) {
        done && done() 
    })
});

gulp.task('imagemin', function(){
    gulp.src('src/images/*')
    .pipe(imagemin({
            optimizationLevel: 5, //类型：Number  默认：3  取值范围：0-7（优化等级）
            progressive: true, //类型：Boolean 默认：false 无损压缩jpg图片
            interlaced: true, //类型：Boolean 默认：false 隔行扫描gif进行渲染
            multipass: true //类型：Boolean 默认：false 多次优化svg直到完全优化
        }))
    .pipe(gulp.dest('dist.min/images'))
    .pipe(notify({message:"压缩成功"}))
    .on('end', function(done) {
        done && done() 
    })
});

gulp.task('jsmin', function (cb) {
  pump([
        gulp.src('src/js/*.js'),
        uglify(),
        gulp.dest('dist.min/js')
    ],
    cb
  );
});

//有需要的用的文件拷贝到dist下
gulp.task('creat:dist',function(){
    return gulp.src('src/js/*.js')
    .pipe(gulp.dest('dist/js')),

    gulp.src(['src/*.html'])
    .pipe(gulp.dest('dist')),

     gulp.src('src/images/*')
    .pipe(imagemin())
    .pipe(gulp.dest('dist/images')),

    gulp.src('src/sass/*')
    .pipe(gulp.dest('dist/sass')),

    gulp.src('src/css/*.css')
     .pipe(gulp.dest('dist/css'))
})

//压缩包
gulp.task('zip:dist', function(){
    return gulp.src(['dist/**/*','!dist/zip/'])
    .pipe(zip('lzo' + nowTime() + '.zip'))
    .pipe(gulp.dest('dist/zip'))
    .on('end', function(done) {
        done && done() 
    })
});
gulp.task('zip:dist.min', function(){
    return gulp.src(['dist.min/**/*','!dist.min/zip/'])
    .pipe(zip('lzo' + nowTime() + '.zip'))
    .pipe(gulp.dest('dist.min/zip'))
    .on('end', function(done) {
        done && done() 
    })
});

function nowTime(){
    var time = new Date();

    var str = '';

    var y = time.getFullYear();
    var m = time.getMonth();
    var d = time.getDay();
    var h = time.getHours();
    var f = time.getMinutes();
    var s = time.getMilliseconds();


    str += zero(y)
    str += zero(m)
    str += zero(d)
    str += zero(h)
    str += zero(f)
    str += zero(s)

    return str;
}
function zero(date){
    date = date.toString();
    if(date.length < 2){
       date = '0' + date;
    }
    return date;
}

// ===============================功能类
// ===================获取类任务
gulp.task("getJquery", function(done) {
    return gulp.src("./node_modules/jquery/dist/jquery.min.js").pipe(gulp.dest("src/js")).on('end', function() {
        done && done()
    })
})

gulp.task("getFlexible", function(done) {
    return gulp.src("./node_modules/flexible/bin/flexible.bin.js").pipe(gulp.dest("src/js")).on('end', function() {
        done && done()
    })
})

gulp.task("choreographer", function(done) {
    return gulp.src(["./node_modules/**/**/choreographer.min.js","./node_modules/**/**/Animation.js"]).pipe(gulp.dest("src/es6")).on('end', function() {
        done && done()
    })
})
// =================== 注释逻辑判断
gulp.task('html', function() {
  gulp.src('*.html')
    .pipe(preprocess({context: { NODE_ENV: 'production', DEBUG: true}})) //To set environment variables in-line 
    .pipe(gulp.dest('dist'))
});


gulp.task("creat:min:dist",gulp.parallel('htmlmin','jsmin','cssmin','imagemin'))

gulp.task('default',gulp.series('sass',gulp.parallel('es6','extend','watch')))

//'browserSyncServer'

